import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:card_swiper/card_swiper.dart';
import 'package:common_utils/common_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:taonile/entity/product_detail_entity.dart';
import 'package:taonile/http/web_path.dart';
import 'package:taonile/routers/routers.dart';
import 'package:taonile/utils/singleton_manager.dart';
import 'package:webview_flutter/webview_flutter.dart';

import '../config/config.dart';
import '../http/api.dart';
import '../utils/common_utils.dart';
import '../utils/string_utils.dart';
import '../utils/user_utils.dart';
import '../views/number_controller_widget.dart';

class StoreDetailPage extends StatefulWidget {
  String storeId = '';

  StoreDetailPage({Key? key, this.storeId = ''}) : super(key: key);

  @override
  State<StoreDetailPage> createState() => _StoreDetailPageState();
}

class _StoreDetailPageState extends State<StoreDetailPage> {
  late WebViewController controller;
  double _webHeight = 750.w; //去计算得到网页的高度，然后设置高度
  late double _originalHeight; //原高度

  var guigeSubIndex = [];
  var spuCurrent = '选择规格';
  var buyNum = '1';
  var bottomPopHeight = 530.w;

  // ProductDetailEntity entity = ProductDetailEntity();
  var imgs = [];

  @override
  void initState() {
    super.initState();
    controller = WebViewController();
    controller.setJavaScriptMode(JavaScriptMode.unrestricted);
    controller.setBackgroundColor(const Color(0x00000000));

    getProductDetal();
    controller.setNavigationDelegate(
      NavigationDelegate(onPageFinished: (url) async {
        //获取webView原始高度
        var originalHeight =
            await controller.runJavaScriptReturningResult("document.body.offsetHeight;");
        print('网页高度1-----$originalHeight');
        _originalHeight = double.parse(originalHeight.toString());
        setState(() {
          _webHeight = _originalHeight / 2.8;
          if (_webHeight > 3500) {
            _webHeight = 3500;
          }
        });
        print('网页高度2-----$_originalHeight');
      }),
    );
    //LogUtil.v('${Config.webUrl}${WebPath.productDetail}${widget.productId}');
    controller.loadRequest(Uri.parse('${Config.webUrl}${WebPath.productDetail}${widget.storeId}'));
  }

  getProductDetal() async {
    // dynamic result = await Api.goodsDetail("/${widget.productId}");
    // setState(() {
    //   entity = ProductDetailEntity.fromJson(result);
    //   guigeSubIndex.clear();
    //   for (var element in entity.data.spec) {
    //     guigeSubIndex.add(0);
    //   }
    //   getSpecStr();
    //   imgs = entity.data.img;
    // });
  }

  collection() async {
    // dynamic result = await Api.collection({'id': widget.productId, 'type': 'goods'});
    // setState(() {
    //   var jsonResult = jsonDecode(jsonEncode(result));
    //   if (jsonResult['code'] == 1) {
    //     EasyLoading.showToast(jsonResult['msg']);
    //
    //     getProductDetal();
    //   }
    // });
  }

  var tags = ['休闲、足浴', '2000人关注'];

  getSearchGuess(int index) {
    return InkWell(
      onTap: () {},
      child: Container(
        width: StringUtils.getStringWidth(tags[index], 19.sp) + 15,
        height: 30.w,
        decoration: BoxDecoration(
          color: Colors.transparent,
          borderRadius: BorderRadius.circular(20.w),
          border: Border.all(color: Config.colorMain, width: 1.w),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              tags[index],
              style: TextStyle(color: Config.colorMain, fontSize: 18.sp),
            ),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      bottomNavigationBar: Container(
        decoration: const BoxDecoration(color: Config.colorBg),
        height: 100.w,
        width: 750.w,
        alignment: Alignment.center,
        padding: EdgeInsets.symmetric(horizontal: 30.w),
        child: Container(
          width: double.infinity,
          child: ElevatedButton(
            clipBehavior: Clip.antiAlias,
            onPressed: () async {
              Routes.navigateTo(context, Routes.storePay);
            },
            style: ElevatedButton.styleFrom(shape: const StadiumBorder()),
            child: const Text('消费付款'),
          ),
        ),
      ),
      body: Container(
        width: double.infinity,
        color: Config.colorBg2,
        height: double.infinity,
        child: Stack(children: [
          //中部内容部分
          SingleChildScrollView(
            scrollDirection: Axis.vertical,
            child: Column(
              children: [
                SizedBox(
                  //轮播
                  height: 450.w,
                  child: Swiper(
                    itemBuilder: (BuildContext context, int index) {
                      return CachedNetworkImage(
                        imageUrl: imgs[index],
                        fit: BoxFit.fill,
                        width: 750.w,
                        height: 390.w,
                        errorWidget: (context, url, error) {
                          return Image.asset(
                            'assets/images/bg_default_400.png',
                            width: 750.w,
                            height: 390.w,
                            fit: BoxFit.fill,
                          );
                        },
                      );
                    },
                    onTap: (index) {},
                    loop: false,
                    autoplay: false,
                    layout: SwiperLayout.DEFAULT,
                    // itemCount: entity.data.img.length,
                    itemCount: imgs.length,
                    // viewportFraction: 0.7,
                    // scale: 0.8,
                    pagination: SwiperPagination(
                      builder: DotSwiperPaginationBuilder(
                          // size: Size(20.w, 4.w),
                          // activeSize: Size(20.w, 4.w),
                          size: 15.w,
                          activeSize: 15.w,
                          activeColor: Config.colorMain,
                          color: Config.colorWhite),
                    ),
                  ),
                ),
                //店铺主要信息
                Container(
                  padding: EdgeInsets.symmetric(horizontal: 30.w, vertical: 30.w),
                  decoration: BoxDecoration(color: Config.colorBg),
                  width: double.infinity,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text(
                            '雅诗兰黛官方旗舰店',
                            softWrap: false,
                            style: TextStyle(color: Config.colorText1, fontSize: 26.sp),
                          ),
                          Text(
                            '09:00-22:00',
                            softWrap: false,
                            style: TextStyle(color: Config.colorText3, fontSize: 23.sp),
                          ),
                        ],
                      ),
                      Padding(padding: EdgeInsets.only(top: 16.w)),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Wrap(
                            spacing: 15.w,
                            runSpacing: 15.w,
                            children: List.generate(tags.length, (index) => getSearchGuess(index)),
                          ),
                          Row(
                            children: [
                              Icon(
                                Icons.location_on_outlined,
                                size: 25.w,
                                color: Config.colorText1,
                              ),
                              Text(
                                '500m',
                                softWrap: false,
                                style: TextStyle(color: Config.colorText1, fontSize: 23.sp),
                              ),
                            ],
                          ),
                        ],
                      ),
                      Padding(padding: EdgeInsets.only(top: 16.w)),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text(
                            '周一至周五可消费',
                            softWrap: false,
                            style: TextStyle(color: Config.colorText1, fontSize: 23.sp),
                          ),
                          Text(
                            '999人已消费',
                            softWrap: false,
                            style: TextStyle(color: Config.colorText3, fontSize: 23.sp),
                          ),
                        ],
                      ),
                      Padding(padding: EdgeInsets.only(top: 16.w)),
                      Wrap(
                        spacing: 15.w,
                        runSpacing: 15.w,
                        children: List.generate(tags.length, (index) => getSearchGuess(index)),
                      ),
                      Divider(
                        height: 40.w,
                        thickness: 2.w,
                        color: Config.colorDivider,
                      ),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Row(
                            children: [
                              Icon(
                                Icons.location_on_outlined,
                                size: 25.w,
                                color: Config.colorText1,
                              ),
                              Text(
                                '宝安46区宜化新村102号',
                                softWrap: false,
                                style: TextStyle(color: Config.colorText1, fontSize: 23.sp),
                              ),
                            ],
                          ),
                          Icon(
                            Icons.phone,
                            size: 28.w,
                            color: Config.colorText1,
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
                //详情
                Container(
                  width: double.infinity,
                  margin: EdgeInsets.only(top: 20.w),
                  padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 22.w),
                  decoration: BoxDecoration(color: Config.colorBg),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Padding(
                        padding: EdgeInsets.only(top: 15.w),
                      ),
                      Container(
                        width: 750.w,
                        height: _webHeight,
                        child: WebViewWidget(
                          controller: controller,
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
          Container(
            //顶部标题栏
            decoration: const BoxDecoration(color: Colors.transparent),
            height: 100.w,
            alignment: Alignment.centerLeft,
            margin: EdgeInsets.only(top: 40.w),
            padding: EdgeInsets.symmetric(horizontal: 30.w),
            child: InkWell(
              onTap: () {
                Routes.router.pop(context);
              },
              child: Container(
                padding: EdgeInsets.only(left: 15.w),
                decoration: BoxDecoration(
                  color: Config.colorBg,
                  borderRadius: BorderRadius.circular(35.w),
                ),
                width: 70.w,
                height: 70.w,
                child: Icon(
                  Icons.arrow_back_ios,
                  size: 45.w,
                ),
              ),
            ),
          ),
        ]),
      ),
    );
  }
}
